package com.jintoufs.service.weixin.impl;

/**
 * crateTime:2017/5/22 15:03
 * author:administrator
 * description:请写注释
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.service.user.UserService;
import com.jintoufs.service.weixin.CoreService;
import com.jintoufs.util.http.HttpRequestUtils;
import com.jintoufs.util.weixin.AccessTokenUtil;
import com.jintoufs.util.weixin.MessageUtil;
import com.jintoufs.util.weixin.TextMessage;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("coreService")
public class CoreServiceImpl implements CoreService {

    public static Logger log = Logger.getLogger(CoreServiceImpl.class);
    @Resource
    private UserService userService;
    @Value("${appId}")
    private String appId;
    @Value("${secret}")
    private String secret;
    @Value("${service_appId}")
    private String serviceAppId;
    @Value("${service_secret}")
    private String serviceSecret;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private CustomerService customerService;

    @Override
    public String processRequest(HttpServletRequest request) {
        String respMessage = null;
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");

            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");

            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(new Date().getTime());
            textMessage.setMsgType("1");
            textMessage.setFuncFlag(0);

            String respContent = "";
            System.out.println("requestMap:" + requestMap);
            if (msgType.equals(Constants.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");

                if (eventType.equals(Constants.EVENT_TYPE_SUBSCRIBE)) {
                    // 关注
                    respContent = "感谢您关注偶,这里会给您提供最新的公司资讯和公告！\n";
                    //TODO 关注后，将该用户增加到user中，在登陆的时候进行比对，如果unionId相同，则是同一个用户，并删除掉这user
                    String accessToken = dictionaryService.getAccessToken("service_AccessToken");
                    if (accessToken == null || "".equals(accessToken)) {
                        accessToken = AccessTokenUtil.getAccessToken(serviceAppId, serviceSecret);
                        List<Dictionary> dictionaryList = dictionaryService.getDicByKeyNo("service_AccessToken");
                        if (!dictionaryList.isEmpty()) {
                            Dictionary dictionary = dictionaryList.get(0);
                            dictionary.setCaption(accessToken);
                            dictionaryService.update(dictionary);
                        }
                    }
                    System.out.println("accessToken:" + accessToken);
                    String url = "https://api.com.jintoufs.service.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + requestMap.get("FromUserName") + "&lang=zh_CN";
                    String userJson = HttpRequestUtils.httpGet(url);
                    System.out.println("userJson:" + userJson);
                    JSONObject jsonObject = JSON.parseObject(userJson);
                    String unionId = jsonObject.get("unionid").toString();
                    String openId = jsonObject.get("openid").toString();

                    Customer user = new Customer();
                    user.setUserName(openId);
                    user.setRealName(openId);
                    user.setPassword("666666");
                    user.setOpenServiceId(openId);
                    user.setStatus(1);
                    user.setUnionId(unionId);
                    Customer entity = customerService.add(user);
                    System.out.println("User:" + entity.toString());
                } else if (eventType.equals(Constants.EVENT_TYPE_UNSUBSCRIBE)) {
                    // 取消关注,用户接受不到我们发送的消息了，可以在这里记录用户取消关注的日志信息
                }
            }
            textMessage.setContent(respContent);
            respMessage = MessageUtil.textMessageToXml(textMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print("respMessage:" + respMessage);
        return respMessage;
    }
}